package com.hand.exam.filter;


import com.alibaba.fastjson.JSON;
import com.hand.exam.constant.ErrorMsg;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author 马旭阳
 * @date2019/7/17
 */
@Component
@WebFilter(filterName = "PerFilter",urlPatterns = "/*")
@Order(99)
public class PerFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("PerFilter init");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest = (HttpServletRequest)servletRequest;
        String userId = httpServletRequest.getHeader("id");
        HttpServletResponse httpServletResponse = (HttpServletResponse)servletResponse;

        if (userId!=null) {
            filterChain.doFilter(servletRequest,servletResponse);
            httpServletResponse.setStatus(200);
        }else {
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json");
            ErrorMsg errorMsg = new ErrorMsg("no no no", "请添加用户头信息");
            PrintWriter printWriter = servletResponse.getWriter();
            String msgJs = JSON.toJSONString(errorMsg);
            printWriter.print(msgJs);
            printWriter.close();
            httpServletResponse.setStatus(403);
        }


    }

    @Override
    public void destroy() {

        System.out.println("PerFilter destroy");
    }

}

